import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import * as moment from 'moment';
import {Http, RequestOptions, Headers} from '@angular/http';
import {adSystemApiUrl} from 'config/api';
import {LocalStorageService} from '../../lib/service/local-storage.service';

@Injectable()
export class OauthService {

  constructor(private http: Http, private router: Router, private localStorageService: LocalStorageService) {
  }

  doLogin(username, password) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({account: username, password: password});
    return this.http.post(adSystemApiUrl + '/v1/member/auth/login', body, options).map(response => response.json());
  }

  doAdminLogin(username, password) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({account: username, password: password});
    return this.http.post(adSystemApiUrl + '/v1/admin/auth/login', body, options).map(response => response.json());
  }

  // 刷新
  doRefresh() {
    let auth,type;
    if (!!this.localStorageService.getUserInfo()) {
      auth = this.localStorageService.getUserInfo();
      type = 'member';
    } else if (!!this.localStorageService.getAdminInfo()) {
      auth = this.localStorageService.getAdminInfo();
      type = 'admin';
    } else {
      return false;
    }
    // 创建时间
    const time = parseInt(auth.time, 10);
    // 过期时间
    const expireTime = time + 3600;
    // 当前时间
    const nowTime = parseInt(moment().format('X'), 10);
    // 过期
    if (expireTime < nowTime) {
      alert('登录信息过期，请重新登录');
      this.clear();
      // this.router.navigate(['/home/index']);
      location.href = '/';
      return false;
    }

    if ((expireTime - 600) <= nowTime&&nowTime <= (expireTime - 200)) {
        if (type == 'member') {
          this.getMemberToken().subscribe(
            res => {
              if (res.code === 2000) {
                auth.time = nowTime;
                this.localStorageService.setUserInfo(auth);
                this.localStorageService.setToken(res.data);
              }
            }
          );
        } else {
          this.getAdminToken().subscribe(
            res => {
              if (res.code === 2000) {
                auth.time = nowTime;
                this.localStorageService.setAdminInfo(auth);
                this.localStorageService.setToken(res.data);
              }
            }
          );
        }
    }

    return false;
  }

  // 获取access token
  getAccessToken() {
    const auth = this.localStorageService.getToken();
    if (auth) {
      return auth.access_token;
    }
    return '';
    /*if (!auth) {
     return '';
     }
     // 创建时间
     const time = parseInt(auth.time, 10);o
     // 过期时间
     const expireTime = time + 3600;
     // 当前时间
     const nowTime = parseInt(moment().format('X'), 10);
     // 过期
     if (expireTime < nowTime) {
     console.log('过期');
     this.clear();
     return '';
     }
     console.log(auth);
     return auth.access_token;*/
  }

  // 退出登录
  clear() {
    localStorage.clear();
    // this.router.navigate(['/home/index']);
    location.href = '/';
  }

  // 是否登录
  isLogin(): boolean {
    const token = this.getAccessToken();
    return token && token != null;
  }

  // 获取登录的用户信息
  // getUser() {
  //   return JSON.parse(localStorage.getItem('user'));
  // }

  getMemberToken() {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const token = this.localStorageService.getToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token.access_token);
    }
    return this.http.get(adSystemApiUrl + '/v1/member/auth/refresh', options).map(response => response.json());
  }

  getAdminToken() {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const token = this.localStorageService.getToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token.access_token);
    }
    return this.http.get(adSystemApiUrl + '/v1/admin/auth/refresh', options).map(response => response.json());
  }

  getTuikeToken() {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const token = this.localStorageService.getToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token.access_token);
    }
    return this.http.get(adSystemApiUrl + '/api/v1/admin/rbac/refresh', options).map(response => response.json());
  }
}
